// Cookie
function createCookie(name,value,days) {
        if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
        } else {
                var expires = "";
        }
        document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
}
function eraseCookie(name) {
        createCookie(name, "", -1);
}

// Bottom of page
function allStuff() {
        var $window = $(window),
                $body = $('body'),
                $dataAuthor = $('[data-author="Najwa Rahman$"]'),
                $topLink = $('#gotop'),
                $checkerBox = $('#reader'),
                $viewPort = $('html, body'),
                $ulSpy = $('ul.spy'),
                $blogStatus = $('#status'),
                $updateBoard = $blogStatus.find('#pengumuman'),
                $nav = $('#taufik'),
                $shockElem = $body.find('*'),
                $pageLoader = $('#page-loader'),
                $openFrame = $('.openFrame'),
                $myComments = $('#comments'),
                $commentBlock = $myComments.find('#cm_block'),
                $ansButton = $('.answer-this-comment'),
                $commentForm = $('#comment-form'),
                $commentEditor = $('#comment-editor'),
                $commentVideo = $myComments.find('.video'),
                $fiddleScreen = $('.jsfiddle-demo'),
                $myDescription = $('abbr, acronym'),
                $emoBar = $('#respond p b'),
                $sidebarWrapper = $('#sidebar-wrapper'),
                $labelWidget = $sidebarWrapper.find('#Label1'),
                $togglePre = $('#togglePre'),
                $topRibbon = $('#top-ribbon'),
                $searchBox = $('#cse-search-box'),
                $subscribeForm = $topRibbon.find('#subscribeform'),
                $subscribeButton = $('.subscribe'),
                $closeForm = $('.closeform'),
                $opener = $('#openab'),
                $closer = $('#closeab'),
                $aboutPanel = $('#about'),
                $archiveToggler = $('.archivedate').find('.toggle'),
                $fadeElem = $('#cse-search-box, .iklan-banner, #main, #reader, #alexa'),
                $slideElem = $('#header, #main-wrapper, #sidebar-wrapper, #iklan-wrapper, .sidebarbox'),
                alertImg = "";

        // Some elements...
        $body.removeClass('init').append('<div id="alert-box" class="hidden"><div class="message"></div></div><span id="loadingtext"></span>').on("click", function() {
                $('.emoKey').remove();
        });
        var $alertBox = $('#alert-box'),
                $loadingText = $('#loadingtext');
        // Rewrite my old blog author name
        $('.cm_name a:contains(Najwa Rahman)').html('Najwa Rahman').closest('.cm_entry').prepend('<span class="author-mark"></span>');
        // Emoticon dialog
        $emoBar.one("click", function() {
                $alertBox.fadeIn(600).children().html('Untuk menyisipkan emotikon setidaknya Anda harus menambahkan satu spasi di depan. Jangan pernah melupakan itu atau emotikon Anda tidak bisa diterjemahkan<div class="button-group"><button class="close">OK</button></div>');
        });
        $alertBox.on("click", ".close", function() {
                $alertBox.fadeOut();
        });
        // View my Profile
        function viewProfile() {
                $('#taufik li ul').slideUp();
                $topRibbon.stop().animate({top:-350}, 700, function() {
                        $fadeElem.fadeOut(700, function() {
                                $aboutPanel.slideDown(1000, function() {
                                        $(this).animate({width:"60%"}, 600);
                                });
                                $slideElem.slideUp(1000);
                        });
                });
        }
        function hideProfile() {
                $fadeElem.fadeIn(700, function() {
                        $topRibbon.stop().animate({top:0}, 600, function() {
                                $aboutPanel.animate({width:"90%"}, 600, function() {
                                        $(this).slideUp(700);
                                });
                        });
                });
        }
        $opener.on("click", function() {
                if ($window.scrollTop() > 100) {
                $viewPort.stop().animate({scrollTop:0}, 'slow', viewProfile);
                } else {
                        viewProfile();
                }
                return false;
        });
        $closer.on("click", function() {
                $slideElem.slideDown(1000, hideProfile);
                return false;
        });
        // Sliding ribbon based on input focus
        if ($topRibbon.is(':visible')) {
                var ribbonMoveDistance = $topRibbon.outerWidth() - ($searchBox.offset().left - $topRibbon.offset().left) + 17;
                $searchBox.find('input').focus(function() {
                        $topRibbon.stop().animate({marginRight:ribbonMoveDistance}, 1000);
                }).focusout(function() {
                        $topRibbon.stop().animate({marginRight:0}, 1000);
                });
        }
        // Loading animation
        var siteURL = "http://" + top.location.host.toString(),
                $internalLinks = "a[href^='" + siteURL + "'], a[href^='/'], a[href^='./'], a[href^='../']";
        $('#out-shadow').on("click", $internalLinks, function() {
                $pageLoader.fadeIn(1500).delay(7000).fadeOut(1000);
        });
        $openFrame.on("click", function() {
                var urlFrame = $(this).attr('href');
                $pageLoader.append('<iframe id="frame1" src="' + urlFrame + '" frameborder="0" scrolling="auto"></iframe>').fadeIn(1500).on("click", function() {
                        $(this).find('iframe, .atribusiform').remove();
                        $(this).slideUp();
                });
                return false;
        });
        // Toggle PRE Tag
        $togglePre.on("change", function() {
                if ($(this).is(':checked')) {
                        $body.addClass('prelight');
                        createCookie('pre', 'prelight', 1000);
                } else {
                        $body.removeClass('prelight');
                        eraseCookie('pre', 'prelight');
                }
        });
        if (readCookie('pre')) {
                $body.addClass('prelight');
                $togglePre.prop('checked', true);
        }
        // Show/hide subscribe form
        $subscribeButton.on("click", function() {
                $topRibbon.stop().animate({
                        width: 328
                }, 2000, "easeInOutExpo", function() {
                        $subscribeForm.fadeIn('slow');
                });
                return false;
        });
        $closeForm.on("click", function() {
                $subscribeForm.fadeOut('slow', function() {
                        $topRibbon.stop().animate({
                                width: 108
                        }, 1000, "easeInOutExpo");
                });
                return false;
        });
        // Accordion sidebar
        $sidebarWrapper.find('.widget-content').hide();
        $sidebarWrapper.find('h2').on("click", function() {
                $sidebarWrapper.find('h2').removeClass('headactive').next().slideUp(900, "easeInOutExpo");
                if ($(this).next().is(':hidden')) {
                        $(this).addClass('headactive').next().slideDown(600, "easeInOutExpo");
                }
        }).last().addClass('headactive').next().show();
        // Label widget hover effect
        $labelWidget.find('a').hover(function() {
                $(this).find('.label-count').slideDown(500, "easeOutBounce");
        }, function() {
                $(this).find('.label-count').fadeOut(400, "easeOutQuart");
        });
        // Comments...
        $myComments.on("click", ".emo", function(e) {
                $('.emoKey').remove();
                $(this).after('<input type="text" size="6" class="emoKey" value=" '+this.alt+'" />');
                $('.emoKey').trigger("select");
                e.stopPropagation();
        }).find('.komentar-spam').each(function(allowLinks, commentContents) {
                allowLinks = $(this).find('a:not(.allow)');
                commentContents = $(this).html();
                txtContents = commentContents.replace(/<br>/ig, "\n")
                        .replace(/&/g, "&amp;")
                        .replace(/</g, "<")
                        .replace(/>/g, ">")
                        .replace(/<pre>/ig, "<i rel=\"pre\">")
                        .replace(/<code>/ig, "<i rel=\"code\">")
                        .replace(/<blockquote>/ig, "<b rel=\"quote\">")
                        .replace(/<h([1-6])>/ig, "<b rel=\"h$1\">")
                        .replace(/<\/(code|pre)>/ig, "<\/i>")
                        .replace(/<\/(blockquote|h[1-6])>/ig, "<\/b>");
                if (allowLinks.length) {
                        $(this).html('Komentar Anda telah dihapus/disembunyikan untuk alasan keamanan dan kenyamanan pembaca lain. Kemungkinan hal ini terjadi karena Anda menuliskan komentar disertai dengan munculnya tautan-tautan yang tidak diperlukan pembaca/tidak sesuai dengan diskusi. Tapi jika bukan itu masalahnya, Saya harap Anda bersedia mencoba menuliskan komentar Anda kembali tanpa mencantumkan tautan/link aktif yang tidak diperlukan. Berikut ini adalah salinan yang mungkin Anda perlukan dari komentar lama yang baru Anda tuliskan sebelum ini:<textarea spellcheck="false">' + txtContents + '</textarea>Terima kasih banyak atas kontribusi Anda di blog eksperimen ini. Salam, <strong>Administrator <big>&hearts;</big></strong><br>').addClass('deleted-by-js').closest('.cm_wrap').find('.cm_reply a').remove();
                }
        });
        // Comments manipulation
        function repTag(old, newTag) {
                $commentBlock.find(old).replaceWith(function() {
                        return $(newTag).html($(this).contents());
                });
        }
        function textToAttr(old, newTag, attr) {
                $commentBlock.find(old).replaceWith(function() {
                        return $(newTag).attr(attr, $(this).text());
                });
        }
        repTag('i[rel="pre"]','<pre></pre>');
        repTag('i[rel="code"]','<code></code>');
        repTag('b[rel="quote"]','<blockquote></blockquote>');
        repTag('b[rel="h1"]','<h1></h1>');
        repTag('b[rel="h2"]','<h2></h2>');
        repTag('b[rel="h3"]','<h3></h3>');
        repTag('b[rel="h4"]','<h4></h4>');
        repTag('b[rel="h5"]','<h5></h5>');
        repTag('b[rel="h6"]','<h6></h6>');
        repTag('em[rel="note"]','<cite class="note"></cite>');
        textToAttr('i[rel="anchor"]', '<a class="allow">[link]</a>', 'href');
        textToAttr('i[rel="image"]', '<img class="center incomment" alt="Loading...">', 'src');
        var $commentImages = $('.incomment');
        $commentImages.each(function(link) {
                link = $(this).attr('src');
                $(this).wrap('<a class="center allow" href="'+link+'" target="_blank"></a>');
                $(this).attr('src', link.replace(/\/s(640|1600)/g, "/s400"));
        });
        var $codeRef = $('.post > code, div > code, p > code'),
                $pre = $('pre');
        $codeRef.each(function() {
                $(this).wrapInner('<a class="allow" title="Telusuri makna kode ini" href="/p/cari-artikel.html?q=' + encodeURIComponent($(this).text()) + '" target="_blank"></a>');
        });
        $pre.attr('title', 'Klik ganda untuk menyeleksi semua kode!').on("dblclick", function() {
                var refNode = $(this)[0], selection, range;
                if($.browser.msie) {
                        range = document.body.createTextRange();
                        range.moveToElementText(refNode);
                        range.select();
                } else if($.browser.mozilla || $.browser.opera) {
                        selection = window.getSelection();
                        range = document.createRange();
                        range.selectNodeContents(refNode);
                        selection.removeAllRanges();
                        selection.addRange(range);
                } else if($.browser.safari) {
                        selection = window.getSelection();
                        selection.setBaseAndExtent(refNode, 0, refNode, 1);
                }
        });
        // Thread comment form
        var source = ($commentEditor.length) ? $commentEditor.attr('src').split('#') : "";
        $ansButton.on("click", function() {
                $alertBox.hide();
                $commentEditor.css('opacity', 0);
                $ansButton.removeClass('clicked');
                $(this).addClass('clicked');
                var start = source[0], end = source[1],
                        replyFrame = start + '&parentID=' + $(this).data('rel').substr(1) + '#' + end,
                        $goTo = $(this).closest('.cm_wrap');
                $commentForm.appendTo($goTo);
                $viewPort.scrollTop($goTo.offset().top - 30);
                $loadingText.html('<span>Memuat...</span>');
                $commentEditor.attr('src', replyFrame).on("load", function() {
                        $(this).css('opacity', 1);
                        $loadingText.html('');
                });
                return false;
        });
        $myComments.on("click", "#cancel-answer", function() {
                var ofs = $('#comment-editor-src').attr('href');
                $loadingText.html('<span>Memuat...</span>');
                $commentForm.appendTo($myComments);
                $commentEditor.css('opacity', 0).attr('src', ofs + '#' + source[1]).on("load", function() {
                        $(this).css('opacity', 1);
                        $loadingText.html('');
                });
                $ansButton.removeClass('clicked');
                return false;
        });
        $fiddleScreen.each(function(url) {
                url = $(this).data('src');
                $(this).replaceWith('<iframe class="jsfiddle-demo loader" src="' + url + '"></iframe>');
        });
        // Toolpik
        $myDescription.css('cursor', 'help').hover(function(e) {
                var winWidth = $window.width(),
                        winHeight = $window.height();
                $(this).append('<div id="toolpik"><div id="nurrohman"></div><div style="clear:both;"></div></div>');
                $('#nurrohman', '#toolpik').html($(this).attr('title'));
                $(this).removeAttr('title');
                var toolpikWidth = $("#toolpik").outerWidth(),
                        toolpikHeight = $("#toolpik").outerHeight(),
                        top = e.clientY - toolpikHeight / 2,
                        left = e.clientX - toolpikWidth / 2;
                if (top + toolpikHeight > winHeight) {
                        top = winHeight - toolpikHeight - 50;
                } else if (top <= 0) {
                        top = 10;
                }
                if (left + toolpikWidth > winWidth) {
                        left = winWidth - toolpikWidth - 50;
                } else if (left <= 0) {
                        left = 10;
                }
                $('#toolpik').delay(600).fadeIn(1000, function() {
                        $(this).delay(600).animate({top:top-70,left:left}, 2000, "easeOutBack", function() {
                                $(this).animate({top:top}, 400);
                        });
                });
        }, function() {
                $(this).attr('title', $('#nurrohman', '#toolpik').html());
                $('#nurrohman').parent().remove();
        });
        // Spoiler
        $('.spoiler').hide().before('<a class="sp-trigger" href="#" style="font-weight:bold;">Lihat Konten [+]</a>');
        $('.sp-trigger').toggle(function() {
                $(this).text('Tutup [-]').next().show();
                return false;
        }, function() {
                $(this).text('Lihat Konten [+]').next().hide();
                return false;
        });
        // Update Board
        $blogStatus.hover(function() {
                $updateBoard.filter(':not(:animated)').delay(1000).show('slow', "easeOutBack");
        }, function() {
                $updateBoard.stop(true, true).delay(1000).hide('slow', "easeInExpo");
        });
        // Top link
        $window.on("scroll", function() {
                var scrollTop = $(this).scrollTop();
                if (scrollTop > 100) {
                        $topLink.removeAttr('href');
                        $topLink.stop().animate({bottom:0,right:0}, 600);
                        $checkerBox.stop().animate({right:50}, 1000);
                } else {
                        $topLink.stop().animate({bottom:-40,right:-40}, 600);
                        $checkerBox.stop().animate({right:20}, 1000);
                }
        });
        $topLink.on("click", function() {
                $viewPort.stop().animate({scrollTop:0}, 970, "easeInOutQuad");
                return false;
        });
        // simpleSpy hover effect
        $ulSpy.hover(function() {
                $(this).find('img').animate({opacity:1}, 500);
        }, function() {
                $(this).find('img').animate({opacity:0.5}, 300);
        });
        // Drop down menu
        $nav.find('li').hover(function() {
                $('ul', this).filter(':not(:animated)').slideDown(600, "easeOutBounce");
        }, function() {
                $('ul', this).slideUp(600, "easeInExpo");
        }).find('.hidden').removeClass('hidden');
        // Fix my blog archive bug
        $archiveToggler.click(function() {
                if ($(this).parent().hasClass('expanded')) {
                        $(this).find('.zippy').html('►;&#160;');
                        $(this).parent().removeClass('expanded').addClass('collapsed').children('ul').slideUp();
                } else {
                        $(this).find('.zippy').html('▼;&#160;');
                        $(this).parent().removeClass('collapsed').addClass('expanded').children('ul').slideDown();
                }
        });
        function shakeDTE() {
                $('.dte').animate({marginTop:-10},400).animate({marginTop:10},400);
        }
        function kill() {
                setInterval(function() {
                        $shockElem.prepend('<img class="dte-child" style="float:left;cursor:none;display:inline;margin:5px;position:relative;left:'+Math.round(Math.random()*16.5)+'px;top:-'+Math.round(Math.random()*10.2)+'px;z-index:99999;width:'+Math.round(Math.random()*120)+'px;height:auto !important" src="'+alertImg+'"/><img class="dte-child" style="float:right;cursor:none;display:inline;margin:5px;position:relative;left:'+Math.round(Math.random()*14)+'px;top:'+Math.round(Math.random()*107)+'px;z-index:99999;width:'+Math.round(Math.random()*10.2)+'px;height:auto !important" src="'+alertImg+'"/>');
                }, 1000);
                $window.scroll(function() {
                        $shockElem.prepend('<img class="dte-child" style="cursor:none;display:inline;float:left;margin:5px;position:relative;left:'+Math.round(Math.random()*16.5)+'px;top:'+Math.round(Math.random()*107)+'px;z-index:99999;width:'+Math.round(Math.random()*270)+'px;height:auto !important" src="'+alertImg+'"/>');
                });
        }
        // Others
        if (!$dataAuthor.length) {
                $shockElem.css({'text-align':'justify','float':'right','overflow':'visible','padding':0,'margin':0});
                $body.css('overflow','hidden').append('<a href="http://idtutorplus.blogspot.com/"><img class="itp" style="display:block;position:fixed !important;position:absolute;top:40%;left:50%;margin:0 0 0 -60px;z-index:99999" src="'+alertImg+'"/></a>');
                setInterval(shakeDTE, 100);
                setTimeout(kill, 7000);
                if ($('link[rel*="icon"]').length) {
                        $('link[rel*="icon"]').attr('href', 'http://idtutorplus.blogspot.com/favicon.ico');
                } else {
                        $('<link rel="icon" href="http://idtutorplus.blogspot.com/favicon.ico">').appendTo('head');
                }
        }
        // Preloading...
        var urlHash = (window.location.hash) ? window.location.hash.substr(1) : '';
        $window.on("load", function() {
                // Fix my comment jump links bug!
                if(window.location.hash && window.location.hash.indexOf('#c') !== -1) {
                        var $targetElem = $('.' + urlHash),
                                scrollDistance = $targetElem.offset().top - 30;
                        $viewPort.animate({scrollTop:scrollDistance}, 4000, function() {
                                $targetElem.find('.cm_entry').css('border', '2px solid yellow');
                                $targetElem.find('.avatar-image-container').css({
                                        'padding': '0px',
                                        'border': '5px solid yellow'
                                });
                        });
                }
                $commentVideo.each(function() {
                        $(this).attr('src', $(this).attr('lsrc'));
                });
                setTimeout(function() {
                        $('iframe.video:not([src*="youtube.com/embed"])').removeAttr('src').css('background', '#900 url(https://tutorplus.googlecode.com/svn/trunk/personal/images/iframe-fallback.png) no-repeat 50% 50%');
                }, 2000);
                if (!readCookie('disable-notification')) {
                        $loadingText.html('<iframe style="display:block;margin:2px auto 0;width:66px;height:17px;border:none;background:transparent;overflow:hidden;" src="https://tutorplus.googlecode.com/svn/trunk/personal/notification-feed.html"></iframe>');
                }
        });
} allStuff();
